package com.wuuxiang.polestar.admin.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.wuuxiang.polestar.admin.dto.BaseReturnDTO;
import com.wuuxiang.polestar.admin.dto.ConfigDto;
import com.wuuxiang.polestar.admin.dto.PropertyDto;
import com.wuuxiang.polestar.admin.service.property.IPropertyService;
import com.wuuxiang.polestar.admin.service.propertyitem.IPropertyItemService;
import com.wuuxiang.polestar.admin.service.team.ITeamService;
import com.wuuxiang.polestar.admin.utils.OvalUtils;

/**
 * 项目名称：polestar        <br>
 * 类描述：                         <br>
 * 创建人：夏鸿鹏                    <br>
 * 创建时间：2017-11-29 9:24        <br>
 * 修改备注：                        <br>
 */
@RestController
public class ExportController {

    @Autowired
    private IPropertyItemService propertyItemService;
    @Autowired
    private ITeamService teamService;
    @Autowired
    private IPropertyService propertyService;

    @RequestMapping("/polestar/downloadPropertyItems")
    public ResponseEntity<byte[]> downloadPropertyItems(@RequestBody PropertyDto propertyDto) throws IOException {
        BaseReturnDTO baseReturnDTO = new BaseReturnDTO();
        if (OvalUtils.validate(baseReturnDTO, propertyDto)) {
            return null;
        }
        List<ConfigDto> items = propertyItemService.getPropertyItemLst(propertyDto.getTeamName(), propertyDto.getPropertyName());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        List<String> lines = formatPropertyLines(items);
        IOUtils.writeLines(lines, "\r\n", out, Charsets.UTF_8.displayName());
        String fileName = propertyDto.getPropertyName() + ".properties";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        List<String> exposeHeaders = new ArrayList<String>();
        exposeHeaders.add("content-disposition");
        headers.setAccessControlExposeHeaders(exposeHeaders);
        return new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.CREATED);
    }

	@RequestMapping("/polestar/downloadAll")
	public ResponseEntity<byte[]> downloadAll() throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		// 获取所有的项目组
		List<String> teams = teamService.getTeamLst();
		if (teams != null && teams.size() > 0) {
			ZipOutputStream zipOutputStream = new ZipOutputStream(out);
			for (String teamName : teams) {
				// 获取项目的配置文件名称
				List<String> propertys = propertyService.getPropertyLst(teamName);
				if (propertys != null && propertys.size() > 0) {
					for (String propertyName : propertys) {
						List<ConfigDto> items = propertyItemService.getPropertyItemLst(teamName, propertyName);
						List<String> lines = formatPropertyLines(items);
						if (!lines.isEmpty()) {
							ZipEntry zipEntry = new ZipEntry(
									teamName + "/" + propertyName + ".properties");
							zipOutputStream.putNextEntry(zipEntry);
							IOUtils.writeLines(lines, "\r\n", zipOutputStream, Charsets.UTF_8.displayName());
							zipOutputStream.closeEntry();
						}
					}
				}
			}
			zipOutputStream.close();
		} else {
			return null;
		}
		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment", "polesar-all.zip");
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		List<String> exposeHeaders = new ArrayList<String>();
        exposeHeaders.add("content-disposition");
        headers.setAccessControlExposeHeaders(exposeHeaders);
		return new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.CREATED);
	}
    
    private List<String> formatPropertyLines(List<ConfigDto> items) {
        List<String> lines = Lists.newArrayList();
        for (ConfigDto item : items) {
        	// 判断此配置为未发布并且发布值为空的情况下不导出
			if (item.getReleaseStatus() == 0 && Strings.isNullOrEmpty(item.getValue())) {
				continue;
			}
            if (!Strings.isNullOrEmpty(item.getRemark())) {
                lines.add("# " + item.getRemark());
            }
            lines.add(item.getItemName() + "=" + item.getValue());
        }
        return lines;
    }

}
